/***************************************************************************************
 The copyright in this software is being made available under the BSD License, included
 below. This software may be subject to other third party rights,including patent rights,
 and no such rights are granted under this license.

 Regents of the Tsinghua University, Peking University, Zhejiang University, HKUST
 Tsinghua University, Peking University, Zhejiang University, HKUST 2011

 Copyright (c) 2011, Regents of the Tsinghua University, Peking University, Zhejiang
 University, HKUST. All Rights Reserved.

 Redistribution and use in source and binary forms, with or without modification, are
 permitted provided that the following conditions are met:
   * Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   * Neither the names of the copyright holders nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 OF SUCH DAMAGE.
***************************************************************************************/

#include <stdlib.h>
#include <string.h>
#if defined(WIN32) && !defined(__MINGW32__)
#include <IO.H>
#endif

#include "contributors.h"
#include "global.h"
#include "memalloc.h"

/*
*************************************************************************
* Function:Write decoded frame to output file
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

#if defined(WIN32) && !defined(__MINGW32__)
void write_frame( image_t *img,
                  int p_out )
#else
void write_frame( image_t *img,
                  FILE * p_out )
#endif
{
    int j;
    int img_width = ( img->width - img->auto_crop_right );
    int img_height = ( img->height - img->auto_crop_bottom );
    int img_width_cr = ( img_width / 2 );
    int img_height_cr = ( img_height /( chroma_format == 2 ? 1 : 2 ) );   // 422
    byte **output_y, ***output_uv;

#if DEBLOCK
    output_y = p_img_y_dec_deblock;
    output_uv = p_img_uv_dec_deblock;
#else
    output_y = p_img_y_dec;
    output_uv = p_img_uv_dec;
#endif
#if defined(WIN32) && !defined(__MINGW32__)
    {
        unsigned char *buf;
        buf = malloc( img_height * img_width );

        for ( j = 0; j < img_height; j++ )
            memcpy( buf + j * img_width, &( output_y[j][0] ), img_width );
        _write( p_out, buf, img_height * img_width );

        for ( j = 0; j < img_height_cr; j++ )
            memcpy( buf + j * img_width_cr, &( output_uv[0][j][0] ), img_width_cr );
        _write( p_out, buf, img_height_cr * img_width_cr );

        for ( j = 0; j < img_height_cr; j++ )
            memcpy( buf + j * img_width_cr, &( output_uv[1][j][0] ), img_width_cr );
        _write( p_out, buf, img_height_cr * img_width_cr );

        free( buf );
    }
#else
    {
        int i;
        for ( i = 0; i < img_height; i++ )
            for ( j = 0; j < img_width; j++ )
                fputc( output_y[i][j], p_out );

        for ( i = 0; i < img_height_cr; i++ )
            for ( j = 0; j < img_width_cr; j++ )
                fputc( output_uv[0][i][j], p_out );

        for ( i = 0; i < img_height_cr; i++ )
            for ( j = 0; j < img_width_cr; j++ )
                fputc( output_uv[1][i][j], p_out );

        fflush( p_out );
    }

#endif

}

/*
*************************************************************************
* Function:Write previous decoded P frame to output file
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

#if defined(WIN32) && !defined(__MINGW32__)
void write_prev_Pframe( image_t *img, int p_out )
#else
void write_prev_Pframe( image_t *img, FILE * p_out )
#endif
{
    int j;
    int img_width = ( img->width - img->auto_crop_right );
    int img_height = ( img->height - img->auto_crop_bottom );
    int img_width_cr = ( img_width / 2 );
    int img_height_cr = ( img_height / ( chroma_format == 2 ? 1 : 2 ) );   //422
    byte **output_y, ***output_uv;

#if DEBLOCK
    output_y = imgY_prev_deblock;
    output_uv = imgUV_prev_deblock;
#else
    output_y = imgY_prev;
    output_uv = imgUV_prev;
#endif

#if defined(WIN32) && !defined(__MINGW32__)
    {
        unsigned char *buf;
        buf = malloc( img_height * img_width );

        for ( j = 0; j < img_height; j++ )
            memcpy( buf + j * img_width, &( output_y[j][0] ), img_width );
        _write( p_out, buf, img_height * img_width );

        for ( j = 0; j < img_height_cr; j++ )
            memcpy( buf + j * img_width_cr, &( output_uv[0][j][0] ), img_width_cr );
        _write( p_out, buf, img_height_cr * img_width_cr );

        for ( j = 0; j < img_height_cr; j++ )
            memcpy( buf + j * img_width_cr, &( output_uv[1][j][0] ), img_width_cr );
        _write( p_out, buf, img_height_cr * img_width_cr );

        free( buf );
    }
#else
    {
        int i;
        for ( i = 0; i < img_height; i++ )
            for ( j = 0; j < img_width; j++ )
                fputc( output_y[i][j], p_out );

        for ( i = 0; i < img_height_cr; i++ )
            for ( j = 0; j < img_width_cr; j++ )
                fputc( output_uv[0][i][j], p_out );

        for ( i = 0; i < img_height_cr; i++ )
            for ( j = 0; j < img_width_cr; j++ )
                fputc( output_uv[1][i][j], p_out );

        fflush( p_out );
    }

#endif

}

#if TRACE
static int bitcounter = 0;

/*
*************************************************************************
* Function:Tracing bitpatterns for symbols
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

void tracebits( const char *trace_str,
                int len,
                int info,
                int value1 )
{

    int i, chars;

    if ( len >= 34 )
    {
        snprintf( errortext, ET_SIZE, "Length argument to put too long for trace to work" );
        error( errortext, 600 );
    }

    putc( '@', p_trace );
    chars = fprintf( p_trace, "%i", bitcounter );
    while ( chars++ < 6 )
        putc( ' ', p_trace );

    chars += fprintf( p_trace, "%s", trace_str );
    while ( chars++ < 55 )
        putc( ' ', p_trace );

    // Align bitpattern
    if ( len < 15 )
    {
        for ( i = 0; i < 15 - len; i++ )
            fputc( ' ', p_trace );
    }
    // Print bitpattern
    for ( i = 0; i < len / 2; i++ )
    {
        fputc( '0', p_trace );
    }
    // put 1
    fprintf( p_trace, "1" );

    // Print bitpattern
    for ( i = 0; i < len / 2; i++ )
    {
        if ( 0x01 & ( info >> ( ( len / 2 - i ) - 1 ) ) )
            fputc( '1', p_trace );
        else
            fputc( '0', p_trace );
    }

    fprintf( p_trace, "  (%3d)\n", value1 );
    bitcounter += len;

    fflush( p_trace );

}

/*
*************************************************************************
* Function:Tracing bitpatterns
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

void tracebits2( const char *trace_str,
                 int len,
                 int info )
{

    int i, chars;

    if ( len >= 45 )
    {
        snprintf( errortext, ET_SIZE, "Length argument to put too long for trace to work" );
        error( errortext, 600 );
    }

    putc( '@', p_trace );
    chars = fprintf( p_trace, "%i", bitcounter );
    while ( chars++ < 6 )
        putc( ' ', p_trace );
    chars += fprintf( p_trace, "%s", trace_str );
    while ( chars++ < 55 )
        putc( ' ', p_trace );

    // Align bitpattern
    if ( len < 15 )
        for ( i = 0; i < 15 - len; i++ )
            fputc( ' ', p_trace );

    bitcounter += len;
    while ( len >= 32 )
    {
        for ( i = 0; i < 8; i++ )
        {
            fputc( '0', p_trace );
        }
        len -= 8;

    }
    // Print bitpattern
    for ( i = 0; i < len; i++ )
    {
        if ( 0x01 & ( info >> ( len - i - 1 ) ) )
            fputc( '1', p_trace );
        else
            fputc( '0', p_trace );
    }

    fprintf( p_trace, "  (%3d)\n", info );

    fflush( p_trace );

}

/*
*************************************************************************
* Function:Tracing bitpatterns for symbols
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

void tracebits3( const char *trace_str,
                 int len,
                 int info,
                 int value1 )
{
    int i, chars;

    if ( len >= 34 )
    {
        snprintf( errortext, ET_SIZE, "Length argument to put too long for trace to work" );
        error( errortext, 600 );
    }

    putc( '@', p_trace );
    chars = fprintf( p_trace, "%i", bitcounter );
    while ( chars++ < 6 )
        putc( ' ', p_trace );

    chars += fprintf( p_trace, "%s", trace_str );
    while ( chars++ < 55 )
        putc( ' ', p_trace );

    // Align bitpattern
    if ( len < 15 )
    {
        for ( i = 0; i < 15 - len; i++ )
            fputc( ' ', p_trace );
    }
    // Print bitpattern
    for ( i = 0; i < len; i++ )
    {
        if ( 0x01 & ( info >> ( len - i - 1 ) ) )
            fputc( '1', p_trace );
        else
            fputc( '0', p_trace );
    }

    fprintf( p_trace, "  (%3d)\n", value1 );
    bitcounter += len;

    fflush( p_trace );

}
#endif
